import { api, xhrPostJson } from '@/services';

import { MenuDataItem } from '@ant-design/pro-layout';
import { setMenuList, setRouteMap } from '@/utils/local-storage';

const convertMenuList = (resourceTree: any[], routeMap: DynamicObjectAny, routeUrl = '') => {
  const newList: MenuDataItem[] = resourceTree.map((item: any) => {
    const { menuUrl, icon, name, children } = item;

    const routeUrlFinal = `${name},${routeUrl}`;
    if (menuUrl) {
      routeMap[menuUrl] = routeUrlFinal;
    }
    return {
      path: menuUrl || '',
      icon,
      name,
      routes:
        Array.isArray(children) && children.length
          ? convertMenuList(children, routeMap, routeUrlFinal).menuList
          : [],
    };
  });

  return {
    menuList: newList,
    routeMap,
  };
};

interface RemoteMenuDataItem {
  code: string;
  icon: string;
  isLeaf: boolean;
  isRoot: boolean;
  menuUrl: string | null;
  name: string;
  orderNum: number;
  parentCode: string;
  type: string;
  children?: MenuDataItem[];
}

export const getMenuData = () => {
  return xhrPostJson(api.menu, {
    pageCode: 'RESOURCE_L',
    systemCode: 'RHAPSODY',
  }).then((res: any) => {
    const { success, result, message } = res;
    if (success) {
      const { children } = result.find((item: RemoteMenuDataItem) => item.isRoot) || {};

      const { menuList, routeMap } = convertMenuList(children || [], {}, '');

      setMenuList(menuList);
      setRouteMap(routeMap);

      return Promise.resolve(menuList);
    } else {
      return Promise.reject(message);
    }
  });
};
